package com.code.user.config.token;

import com.code.user.btv.bo.AccountBO;
import com.code.user.model.RoleDO;
import com.code.user.model.UserDO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: Yan
 * @date: 2023/4/14
 *
 * 自定义 CustomerAccessTokenConverter 这个类的作用主要用于 AccessToken 的转换,
 * 默认使用 DefaultAccessTokenConverter 这个装换器
 * DefaultAccessTokenConverter 有个 UserAuthenticationConverter，这个转换器作用是把用户的信息放入 token 中，
 * 默认只是放入 username
 */
public class AccessTokenConverterExt extends DefaultAccessTokenConverter {

    public AccessTokenConverterExt() {
        super.setUserTokenConverter(new UserAuthenticationConverter());
    }

    private class UserAuthenticationConverter extends DefaultUserAuthenticationConverter {

        @Override
        public Map<String, ?> convertUserAuthentication(Authentication authentication) {

            AccountBO accountBO = (AccountBO) authentication.getPrincipal();
            UserDO userInfo = accountBO.getUserInfo();

            /*
            Map<String, Object> userInfoWrapper = new HashMap<>();
            userInfoWrapper.put("id", userInfo.getId());
            userInfoWrapper.put("nickname", userInfo.getNickname());
            userInfoWrapper.put("avatar", userInfo.getAvatar());
            userInfoWrapper.put("remark", userInfo.getRemark());
            userInfoWrapper.put("profile", userInfo.getProfile());
            userInfoWrapper.put("gender", userInfo.getGender());
            userInfoWrapper.put("themeColor", userInfo.getThemeColor());
            userInfoWrapper.put("roles", this.getRoleList(accountBO));
            */

            Map<String, Object> response = new LinkedHashMap<>();
            response.put("user_name", userInfo.getNickname());
            // response.put("userInfo", userInfoWrapper);

            if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
                response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
            }
            return response;
        }

        private List<String> getRoleList(AccountBO accountBO) {
            if (CollectionUtils.isEmpty(accountBO.getRoles())){
                return new ArrayList<>();
            }
            return accountBO.getRoles().stream().map(RoleDO::getName).collect(Collectors.toList());
        }

    }
}
